package com.ourteam.system.api;

import org.apache.commons.lang.ArrayUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;

import com.ourteam.frame.web.AbstractSearchModel;
import com.ourteam.frame.web.ApplicationModel;
import com.ourteam.system.dao.ISysRoleActionRelateDAO;
import com.ourteam.system.dao.ISysUserRoleRelateDAO;
import com.ourteam.system.dao.SysActionDAOQueryBean;
import com.ourteam.system.dao.SysRoleActionRelate;
import com.ourteam.system.dao.SysRoleActionRelateDAOFactory;
import com.ourteam.system.dao.SysRoleActionRelateDAOQueryBean;
import com.ourteam.system.dao.SysUserRoleRelate;
import com.ourteam.system.dao.SysUserRoleRelateDAOFactory;
import com.ourteam.system.dao.SysUserRoleRelateDAOQueryBean;
import com.ourteam.system.domain.SystemUserRoleRelate;

public class SystemActionSearchModel extends AbstractSearchModel<SysActionDAOQueryBean> {

	private long sysModuleId;

	public long getSysModuleId() {
		return sysModuleId;
	}

	public void setSysModuleId(long sysModuleId) {
		this.sysModuleId = sysModuleId;
	}

	@Override
	public String getMappedDAOField(String aProperty) {
		return SystemUserRoleRelate.getMappedDAOField(aProperty);
	}
	private static final ISysRoleActionRelateDAO SYS_ROLE_ACTION_RELATE_DAO = SysRoleActionRelateDAOFactory.getSysRoleActionRelateDAO();
	
	private static final ISysUserRoleRelateDAO  SYS_USER_ROLE_RELATE_DAO = SysUserRoleRelateDAOFactory.getSysUserRoleRelateDAO();
	
	

	@Override
	protected void doBuildQueryBean(SysActionDAOQueryBean queryBean) throws Exception {
		//获取当前登录人的角色
		Subject subject = SecurityUtils.getSubject();
		ApplicationModel applicationModel = (ApplicationModel) subject.getPrincipal();
		long userId = applicationModel.getUserId();
		
		SysUserRoleRelateDAOQueryBean sysRoleDAOQueryBean = new SysUserRoleRelateDAOQueryBean();
		sysRoleDAOQueryBean.createCriteria().andUserIdEqualTo(userId);
		SysUserRoleRelate [] sysUserRoleRelates = SYS_USER_ROLE_RELATE_DAO.query(sysRoleDAOQueryBean);
		Long [] roleIds = new Long[sysUserRoleRelates.length];
		for (int i = 0; i < roleIds.length; i++) {
			roleIds[i] = sysUserRoleRelates[i].getId();
		}
		if (roleIds.length>0) {
			SysRoleActionRelateDAOQueryBean queryBean2 = new SysRoleActionRelateDAOQueryBean();
			queryBean2.createCriteria().andRoleIdIn(roleIds);
			SysRoleActionRelate [] sysRoleActionRelates =  SYS_ROLE_ACTION_RELATE_DAO.query(queryBean2);
			if(ArrayUtils.isNotEmpty(sysRoleActionRelates)) {
				Long [] roleactionId = new Long[sysRoleActionRelates.length];
				for (int i = 0; i < sysRoleActionRelates.length; i++) {
					roleactionId[i] = sysRoleActionRelates[i].getActionId();
				}
				queryBean.createCriteria().andModuleIdEqualTo(sysModuleId).andIdIn(roleactionId);
			}

		}else{
			queryBean.createCriteria().andModuleIdEqualTo(sysModuleId);
		}
	}

}
